﻿/// <reference path="jquery-1.4.4.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

(function ($) {
    $.validator.unobtrusive.parseDynamicContent = function (selector) {
        //use the normal unobstrusive.parse method
        $.validator.unobtrusive.parse(selector);

        //get the relevant form
        var form = $(selector).first().closest('form');

        //get the collections of unobstrusive validators, and jquery validators
        //and compare the two
        var unobtrusiveValidation = form.data('unobtrusiveValidation');
        var validator = form.validate();

        $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
            if (validator.settings.rules[elname] == undefined) {
                var args = {};
                $.extend(args, elrules);
                args.messages = unobtrusiveValidation.options.messages[elname];
                $('[name=' + elname + ']').rules("add", args);
            } else {
                $.each(elrules, function (rulename, data) {
                    if (validator.settings.rules[elname][rulename] == undefined) {
                        var args = {};
                        args[rulename] = data;
                        args.messages = unobtrusiveValidation.options.messages[elname][rulename];
                        $('[name=' + elname + ']').rules("add", args);
                    }
                });
            }
        });
    }
})($);

function validateValues(json) {
    if (typeof (json.errors) != "undefined") {

        return false;
    }
    return true;
}

$(document).ready(function () {

    $(".task-form").live("submit", function () {
        var form = $(this);

        if (form.find("#text").val().length == 0) {
            form.find(".error-msg").show();
            return false;
        }
        form.find(".error-msg").hide();

        var options = {
            success: function (json) {
                if (!validateValues(json))
                    return;

                if (form.find("#id").length > 0) {
                    $(".task").show();
                    var id = form.find("#id").val();
                    $("#task" + id).find(".content").html(json.text);
                } else {
                    $("#tasks").append(json.html);
                    $("#text").focus();
                    form.clearForm();
                }
                $(".edit-form").remove();
            },
            error: function (request, textStatus, errorThrown) {
                alert("error save");
                //server errors displaying
            },
            data: { "workBookName": $("#workBookName").val() },
            type: "POST"
        };

        $(this).ajaxSubmit(options);
        return false;
    });

    $("#tasks .task .delete").live("click", function () {
        var taskId = $(this).parents(".task:first").attr("id").replace("task", "");
        if (confirm("Are you sure yuo want to delete it?")) {
            $.ajax({
                type: "POST",
                data: { id: taskId },
                url: "[ApplicationPath]task/delete",
                success: function (json) {
                    $("#task" + taskId).remove();
                },
                error: function (request, textStatus, errorThrown) {
                    alert("error delete");
                    //server errors displaying
                }
            });
        }
        return false;
    });

    $("#tasks .task.notstarted").live("click", notStartedTask);
    $("#tasks .task.active").live("click", activeTask);
    $("#tasks .task.finished").live("click", finishedTask);

    $("#tasks .task .edit").live("click", function () {
        var taskId = $(this).parents(".task").attr("id").replace("task", "");

        $.ajax({
            type: "GET",
            data: { id: taskId },
            url: "[ApplicationPath]task/item",
            success: function (json) {
                $(".task").show();
                $("#task" + taskId).hide();
                $(".edit-form").remove();

                var editForm = $(".task-form.template").clone();
                editForm.removeClass("template");
                editForm.attr("action", "[ApplicationPath]task/update");
                editForm.addClass("edit-form");
                editForm.find("#text").val(json.Text);
                editForm.find("button").html("save");

                editForm.addClass(json.Status.toLowerCase());

                editForm.append("<input type='hidden' name='id' id='id' value='" + taskId + "'/>");

                $("#task" + taskId).after(editForm);
                $.validator.unobtrusive.parseDynamicContent('.edit-form');
                editForm.find("#text").focus();
            },
            error: function (request, textStatus, errorThrown) {
                alert("error edit");
                //server errors displaying
            }
        });

        return false;
    });

    $("#tasks .task").live("mouseover", function () {
        //if ($(this).hasClass("notstarted")) {
        $(this).find(".actions").show();
        //}
    });

    $("#tasks .task").live("mouseleave", function () {
        $(this).find(".actions").hide();
    });
});

function activeTask() {
    var taskId = $(this).attr("id").replace("task", "");
    $.ajax({
        type: "POST",
        data: { id: taskId, workBookName: $("#workBookName").val() },
        url: "[ApplicationPath]task/finish",
        success: function (json) {
            if (!checkError(json)) {
                return;
            }
            var task = $("#task" + taskId);
            task.removeClass("active");
            task.addClass("finished");
        },
        error: function (request, textStatus, errorThrown) {
            alert("error action->");
            //server errors displaying
        }
    });
    return false;
}

function finishedTask() {
    var task = $(this);
    var taskId = task.attr("id").replace("task", "");
    $.ajax({
        type: "POST",
        data: { id: taskId, workBookName: $("#workBookName").val() },
        url: "[ApplicationPath]task/copy",
        success: function (json) {
            if (!checkError(json)) {
                return;
            }
            var newTask = task.clone();
            newTask.removeClass("active");
            newTask.removeClass("finished");
            newTask.addClass("notstarted");
            newTask.attr("id", "task" + json.id);
            newTask.find(".actions").hide();
            $("#tasks").append(newTask);
        },
        error: function (request, textStatus, errorThrown) {
            alert("error action->");
            //server errors displaying
        }
    });
    return false;
}

function notStartedTask() {
    var taskId = $(this).attr("id").replace("task", "");

    if ($("#tasks .task").hasClass("active")) {
        var activeTask = $("#tasks .task.active");
        var activeTaskId = activeTask.attr("id").replace("task", "");

        //finish
        $.ajax({
            type: "POST",
            data: { id: activeTaskId, workBookName: $("#workBookName").val() },
            url: "[ApplicationPath]task/finish",
            success: function (json) {
                activeTask.removeClass("active");
                activeTask.addClass("finished");
                //copy
                $.ajax({
                    type: "POST",
                    data: { id: activeTaskId, workBookName: $("#workBookName").val() },
                    url: "[ApplicationPath]task/copy",
                    success: function (json) {
                        if (!checkError(json)) {
                            return;
                        }
                        var newTask = activeTask.clone();
                        newTask.removeClass("finished");
                        newTask.addClass("notstarted");
                        newTask.attr("id", "task" + json.id);
                        newTask.find(".actions").hide();
                        $("#tasks").append(newTask);
                    },
                    error: function (request, textStatus, errorThrown) {
                        alert("error action->");
                        //server errors displaying
                    }
                });
                //active
                $.ajax({
                    type: "POST",
                    data: { id: taskId, workBookName: $("#workBookName").val() },
                    url: "[ApplicationPath]task/activate",
                    success: function (json) {
                        if (!checkError(json)) {
                            return;
                        }
                        $("#task" + taskId).addClass("active");
                        $("#task" + taskId).removeClass("notstarted");
                    },
                    error: function (request, textStatus, errorThrown) {
                        alert("error action->");
                        //server errors displaying
                    }
                });
            },
            error: function (request, textStatus, errorThrown) {
                alert("error action->");
                //server errors displaying
            }
        });
    } else {
        $.ajax({
            type: "POST",
            data: { id: taskId, workBookName: $("#workBookName").val() },
            url: "[ApplicationPath]task/activate",
            success: function (json) {
                if (!checkError(json)) {
                    return;
                }
                $("#task" + taskId).addClass("active");
                $("#task" + taskId).removeClass("notstarted");
            },
            error: function (request, textStatus, errorThrown) {
                alert("error action->");
                //server errors displaying
            }
        });
    }
    return false;
}

function checkError(json) {
    if (typeof (json.error) != "undefined") {
        alert(json.error.msg);
        return false;
    }
    return true;
}